<template>
  <div>
    <div class="page-container" v-if="!createCouponComponents">
          <!--工具栏-->
          <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
            <el-form :inline="true" :model="filters" :size="size" ref="filters">
              <el-form-item prop="couponName" label="活动名称">
                <el-input v-model="filters.couponName" placeholder="活动名称" style="width:230px"></el-input>
              </el-form-item>
			  <el-form-item prop="id" label="活动ID">
                <el-input v-model="filters.id" placeholder="活动ID" style="width:230px"></el-input>
              </el-form-item>
              <el-form-item prop="couponType" label="优惠券类型">
                <el-select v-model="filters.couponType" placeholder="优惠券类型" style="width:230px">
                      <el-option
                      v-for="item in couponTypes"
                      :key="item.couponType"
                      :label="item.label"
                      :value="item.couponType">
                      </el-option>
                  </el-select>
              </el-form-item>
			  <el-form-item prop="id" label="创建人">
                <el-input v-model="filters.cortea" placeholder="创建人" style="width:230px"></el-input>
              </el-form-item>
              <el-form-item prop="startDate" label="活动时间">
                  <el-date-picker
                      v-model="filters.startDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      format="yyyy-MM-dd"
                      placeholder="活动有效时间始" class="input_postion"
					  style="width:230px">
                  </el-date-picker>
              </el-form-item>
              <el-form-item prop="endDate">
                  <el-date-picker
                      v-model="filters.endDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      format="yyyy-MM-dd"
                      placeholder="活动有效时间止" class="input_postion"
					  style="width:230px">
                  </el-date-picker>
              </el-form-item>
			  <el-form-item prop="channl" label="活动渠道">
                <el-select v-model="filters.channl" placeholder="活动渠道" style="width:230px">
                      <el-option
                      v-for="item in couponTypes"
                      :key="item.couponType"
                      :label="item.label"
                      :value="item.couponType">
                      </el-option>
                  </el-select>
              </el-form-item>
			  <el-form-item prop="channl" label="活动商家">
                <el-select v-model="filters.channl" placeholder="活动商家" style="width:230px">
                      <el-option
                      v-for="item in couponTypes"
                      :key="item.couponType"
                      :label="item.label"
                      :value="item.couponType">
                      </el-option>
                  </el-select>
              </el-form-item>
			  <el-form-item prop="channl" label="活动店铺">
                <el-select v-model="filters.channl" placeholder="活动店铺" style="width:230px">
                      <el-option
                      v-for="item in couponTypes"
                      :key="item.couponType"
                      :label="item.label"
                      :value="item.couponType">
                      </el-option>
                  </el-select>
              </el-form-item>
              <el-row>
                <el-form-item>
                  <kt-button
                    icon="fa fa-search"
                    :label="$t('action.search')"
                    type="primary"
					@click="findPage"
                  />
                </el-form-item>
                <el-form-item>
                  <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetForm('filters')" />
                </el-form-item>
                <el-form-item>
                  <kt-button label="创建活动" @click="createPage()" type="primary" />
                </el-form-item>
                <el-form-item>
                  <kt-button label="通过模板创建活动" type="primary"/>
                </el-form-item>
                <el-form-item>
                  <kt-button label="导出Excel" type="primary" />
                </el-form-item>
              </el-row>
            </el-form>
          </div>
            <div class="tab-container">
              <el-alert :closable="false" style="background-color: #ffffff;color: #ffffff;" title="" type="success" />
              <el-tabs v-model="activeName" style="margin-top:15px;">
                <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
                 <!-- <keep-alive>
                    <tab-pane v-if="activeName==item.key" :type="item.key" />
                  </keep-alive -->
                </el-tab-pane>
              </el-tabs>
			  
			  <!-- jic table表格-->
			  <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
			    <!--表格显示列界面-->
			    <table-column-filter-dialog
			      ref="tableColumnFilterDialog"
			      :columns="columns"
			      @handleFilterColumns="handleFilterColumns"
			    ></table-column-filter-dialog>
			  </div>
			  <!--表格内容栏-->
			  <jic-table
			    :height="350"
			    :data="pageResult"
			    :totalSize="totalSize"
			    :columns="filterColumns"
			    @findPage="findPage"
			    ref="JicTable"
				:showEditOperation="false"
				:showBatchDelete="false"
				:loading="loading"
				@handleDelete="handleDelete"
				:btnList="btnList"
				@closeCoupon="closeCoupon"
				@sendCoupon="sendCoupon"
				:operationWidth="260"
				@submitReview="submitReview"
				@review="review"
				@copyCoupon="copyCoupon"
			  ></jic-table>
			 
			  
            </div>

      <el-dialog title="文件任务列表" :visible.sync="showModel"  width="70%" height="100%" label-width="80px" label-position="right">
        <el-form style="text-align:left" label-width="80px" label-position="right" size="small">

          <el-table :data="tableData" border style="width: 100%" @row-click="handleClick">
            <template>
              <el-table-column prop="businessnumber" label="任务编号" width="180"></el-table-column>
              <el-table-column prop="type" label="任务类型" width="120"></el-table-column>
              <el-table-column prop="operating" label="操作" width="120"></el-table-column>
              <el-table-column prop="status" label="任务状态" width="120"></el-table-column>
              <el-table-column prop="start" label="任务开始时间" width="180"></el-table-column>
              <el-table-column prop="end" label="任务结束时间" width="180"></el-table-column>
              <el-table-column prop="count" label="总记录数" width="90"></el-table-column>
              <el-table-column prop="successcount" label="成功记录数" width="90"></el-table-column>
              <el-table-column prop="errorcount" label="失败记录数" width="90"></el-table-column>
              <el-table-column prop="operatings" label="操作" width="120">
                <template slot-scope="scope">
                  <el-button @click="handleClick(scope.row)" type="text" size="small">下载结果</el-button>
                </template>
              </el-table-column>
              </template>
          </el-table>
        
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:center">
          <el-button @click.native="showModel = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
    <div v-if="createCouponComponents">
      <CouponComponents @viewList="createPage">

      </CouponComponents>
    </div>
	<el-dialog title="审核" :visible.sync="dialogFormVisible">
	  <el-form :model="form">
	    <el-form-item label="审核理由" :label-width="formLabelWidth">
	      <el-input v-model="form.checkRemark" autocomplete="off" type="textarea" rows = "6"></el-input>
	    </el-form-item>
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button type="danger" @click="reviewDialog(6)" size="mini">审核拒绝</el-button>
	    <el-button type="primary" @click="reviewDialog(0)" size="mini">审核通过</el-button>
	  </div>
	</el-dialog>
  </div>
</template>



<script>
import KtButton from "@/views/Core/KtButton";
import JicTable from "@/views/Core/JicTable";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from 'color-name';
import tabPane from './components/TabPaneCouponTheme'
import CouponComponents from './CouponComponents'
export default {
  name: 'Tab',
  components: {
    CouponComponents,
    tabPane ,
    KtButton,
	JicTable,
    TableColumnFilterDialog,
  },
  data() {
    return {
		formLabelWidth: '120px',
		dialogFormVisible:false,
		form:{
			
		},
		row:{
			
		},
       createCouponComponents:true,
       tableData: [],
	   pageResult: {},
	   columns: [],
	   filterColumns: [],
	   totalSize:0,
	   pageRequest:{},
	   loading:true,
      tabMapOptions: [
        { label: '全部', key: '99' },
        { label: '待提交', key: '1' },
        { label: '待审核', key: '2' },
        { label: '未开始', key: '3' },
        { label: '审核未通过', key: '4' },
        { label: '进行中', key: '5' },
		{ label: '已过期', key: '6' },
		{ label: '已关闭', key: '7' },
		{ label: '已失效', key: '8' },
		{ label: '活动草稿', key: '0' },
      ],
      activeName: '99',
      createdTimes: 0,
      showModel:false,
      size: "small",
      filters: {
        deleteFlag:0
      },
    couponTypes:[{'couponType':'0','label':'电子券'},{'couponType':'1','label':'实体券'}],
    couponGiveRules:[{'grantType':1,'label':'指定用户发放'},{'grantType':2,'label':'注册自动发放'},{'grantType':0,'label':'前台领券'},{'grantType':3,'label':'抽奖券'}],
    btnList:[]
	
	};
  },
  methods: {
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
		this.findPage();
      }
    },
    createPage(){
      // this.$router.push("/CreatePromotion");
      this.createCouponComponents = this.createCouponComponents == true ? false : true;
    },
     //查看任务
    lookTask(){
      this.showModel=true;
    },
    handleClick(){
      this.$message({'message':'操作成功','type':'success'})
    },
	
	// 获取分页数据
	findPage: function(data) {
	  /**
	   * 子组件传过来的分页参数
	   * data.start 当前页
	   * data.limit 当前页总条数
	   * */
	  this.loading = true;
	  if(data != null && data.start != null){
	    if(data.start != null){
	      this.pageRequest.pageNum = data.start;
	    }
	    if(data.limit != null){
	      this.pageRequest.pageSize = data.limit;
		  // debugger
	    }
	  }
	
	  let this_ = this;
	  if (this_.filters == undefined || this_.filters == null) {
	    this_.filters = {};
	  }
	  this_.filters.start = this.pageRequest.pageNum;
	  this_.filters.limit = this.pageRequest.pageSize;
	  // this_.filters.grantType = Number(this.filters.grantType);
	  // let param = this_.filters;
	  this.utils.request.couponQueryConfig(this_.filters, function (res) {
		 this_.loading = false;
	    if (res.data.rows.length < 1) {
	      res.data.rows = [];
	      res.data.total = 0;
	    }
		// debugger;
	    this_.$refs.JicTable.findPage({content:res.data.rows,total:res.data.total});
	    // debugger
	    // this_.pageResult = res.data;
	    // this_.totalSize = Number(res.totle);
	  });
	},
	// 处理表格列过滤显示
	displayFilterColumnsDialog: function() {
	  this.$refs.tableColumnFilterDialog.setDialogVisible(true);
	},
	// 处理表格列过滤显示
	handleFilterColumns: function(data) {
	  this.filterColumns = data.filterColumns;
	  this.$refs.tableColumnFilterDialog.setDialogVisible(false);
	},
	// 处理表格列过滤显示
	initColumns: function() {
	  this.btnList = [{
			customLabel:"复制",
			// isShowFommart:function(row){
			// 	return true;
			// },
			isShowMethod:true,
			method:"copyCoupon"
		},{
			customLabel:"关闭",
			isShowMethod:"0",
			// isShowFommart:function(row){
			// 	if(row.couponStatus == 22){
			// 		return true;
			// 	}
			// },
			method:"closeCoupon"
		},
		// {
		// 	"customLabel":"发券",
		// 	"isShowMethod":"0",
		// 	"method":"sendCoupon"
		// },
		{
			customLabel:"提交审核",
			isShowMethod:"4",
			// isShowFommart:function(row){
			// 	if(row.couponStatus == 23){
			// 		debugger
			// 		return true;
			// 	}
			// },
			method:"submitReview"
		}
		,{
			customLabel:"审核",
			isShowMethod:"5",
			method:"review"
		}
		]



	  this.columns = [
		{ prop: "id", label: "ID", minWidth: 60},
		{ prop: "couponName", label: "优惠券名称", minWidth: 120,sortable:false },
	    { prop: "grantType", label: "发券类型", minWidth:100 ,sortable:false ,formatter:function(row, column, cellValue, index){
			//0前台领券,1指定用户发放,2注册自动发放,3抽奖券
			if(row.grantType == 0){
				return "前台领券";
			}else if(row.grantType == 1){
				return "指定用户发放";
			}else if(row.grantType == 2){
				return "注册自动发放"
			}else if(row.grantType){
				return "抽奖券"
			}else{
				return "未知的优惠券类型";
			}
		}},
	    { prop: "couponType", label: "优惠券类型", minWidth: 100 ,sortable:false  ,formatter:function(row, column, cellValue, index){
			if(row.couponType == 0){
				return "电子券";
			}else if(row.couponType == 1){
				return "实体券";
			}else{
				return "未知券类型";
			}
		}},
		{ prop: "costAllocation", label: "营销成本是否分摊", minWidth: 100 ,sortable:false  ,formatter:function(row, column, cellValue, index){
			if(row.costAllocation == 1){
				return "是";
			}else if(row.costAllocation == 2){
				return "否";
			}else{
				return "";
			}
		}},
	    { prop: "amountDeductType", label: "金额抵扣类型", minWidth: 100 ,sortable:false ,formatter:function(row){
			//0金额券,1折扣券
			if(row.amountDeductType == 0){
				return "金额券";
			}else if(row.amountDeductType == 1){
				return "折扣券";
			}else{
				return "未知的抵扣类型";
			}	
		}},
	    { prop: "couponAmount", label: "面值（元）", minWidth: 100,sortable:false  },
	    { prop: "useChannel", label: "使用渠道", minWidth: 70,sortable:false  },
	    { prop: "activityStartTime", label: "券活动日期", minWidth: 260 ,sortable:false ,formatter:function(row){
			if(row.activityStartTime != null && row.activityEndTime != null){
				return row.activityStartTime + " 至 " + row.activityEndTime;
			}	
		}},
	    { prop: "idLimitDayNum", label: "总限领（张）", minWidth: 90 ,sortable:false },
		{ prop: "idLimitNum", label: "每人限领（张）", minWidth: 120,sortable:false  },
		{ prop: "useTotalAmountLimit", label: "使用条件", minWidth: 170,sortable:false ,formatter:function(row){
				return "订单满"+row.useTotalAmountLimit+"元可用";
		}},
		{ prop: "createTime", label: "创建时间", minWidth: 150},
		// { prop: "pName", label: "已发行量/已领取/已使用", minWidth: 120 },
		{ prop: "couponStatus", label: "状态", minWidth: 90 ,sortable:false,formatter:function(row){
			//优惠券状态 0进行中,1已失效,2已关闭,3未开始,4待提交,5待审核,6审核未通过
			if(row.couponStatus == 0){
				return "进行中";
			}else if(row.couponStatus == 1){
				return "已失效";
			}else if(row.couponStatus == 2){
				return "已关闭"
			}else if(row.couponStatus == 3){
				return "未开始"
			}else if(row.couponStatus == 4){
				return "待提交"
			}else if(row.couponStatus == 5){
				return "待审核"
			}else if(row.couponStatus == 6){
				return "审核未通过"
			}
		}}
	  ];
	  var temp = [];
	  $.each(this.columns, function(key, val) {
	    temp.push(val);
	  });
	  this.filterColumns = temp;
	},
	/* 删除 */
	handleDelete: function(data) {
	  if (data != null && data.params != null && data.params.length > 0) {
	    let ids = data.params.map(item => item.id).toString();
	    var params = {};
	    params.couponId = ids;
	    var this_ = this;
	    this.utils.request.couponDeleteConfig(params, function(res) {
	      if (res.code == "0000") {
	        this_.$message({ message: "操作成功", type: "success" });
	        this_.findPage(null);
	      } else {
	        this_.$message({ message: "操作失败, " + res.msg, type: "error" });
	      }
	    });
	  }
	},
	closeCoupon:function (data){
		console.log("-=====>>>关闭")
		console.log(data.row);
		let that = this;
		this.$confirm("确认关闭当前优惠券吗？", "提示", {
		  type: "warning"
		}).then(() => {
		   that.utils.request.couponCloseConfig({"couponId":data.row.couponId},res=>{
			   this.$message({ message: "关闭成功", type: "success" });
			   this.findPage();
		   })	   
		  })
		  .catch(() => {
		  });
		// this.$message({ message: "关闭 暂未开放,等待下一版", type: "success" });
	},
	sendCoupon:function(data){
		console.log("-=====>>>发券")
		console.log(data.row);
		// this.$message({ message: "发券 暂未开放,等待下一版", type: "success" });
	},
	submitReview:function(data){
		console.log("-=====>>>提交审核")
		let that = this;
		const loading = this.$loading({
			lock: true,
			text: '小的正在努力加载中......',
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.8)'
		});
		this.utils.request.couponCheckCoupon({couponId:data.row.couponId,"updateStatus":5},res=>{
			 console.log("提交审核成功");
			 loading.close();
			 that.$message({ message: "提交审核成功", type: "success" });
			 that.findPage();
		})
		
	},
	review:function(data){
		this.dialogFormVisible =  true;
		this.row = data.row;
	},
	reviewDialog:function(data){
		let that = this;
		this.form.couponId = this.row.couponId
		this.form.updateStatus = data;
		that.utils.request.couponCheckCoupon(this.form,res=>{
			if(res.code == "0000"){
				that.dialogFormVisible =  false;
				that.$message({ message: "审核完成", type: "success" });
				that.findPage();
			}else{
				that.$message({ message: "审核失败", type: "error" });
			}
		})
	},
	/* 复制 */
	copyCoupon:function(data){
		let that = this;
		this.$confirm("确认复制当前优惠券吗？", "提示", {
		  type: "warning"
		}).then(() => {
		   that.utils.request.couponCopyConfig({"couponId":data.row.couponId},res=>{
			   this.$message({ message: "复制成功", type: "success" });
			   this.findPage();
		   })	   
		  })
		  .catch(() => {
		  });
	}
  },
  watch: {
    activeName(val) {
		if(val != 99){
			this.filters.couponStatus = val;
		}else{
			this.filters.couponStatus = null;
		}
		this.findPage();
      // this.$router.push(`${this.$route.path}?tab=${val}`)
    }
  },  
  created() {
    // init the default selected tab
    const tab = this.$route.query.tab
    if (tab) {
      this.activeName = tab
    }
  },
 
  mounted() {
	  this.initColumns();
  },
  
};
</script>

<style scoped>
</style>